package com.cashmate.hibernate.dao;

import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

//EXTEND ME
public class DAO {

    private static final Logger log = Logger.getLogger(DAO.class);
    @SuppressWarnings("unchecked")
    private static final ThreadLocal session = new ThreadLocal();
    private static final SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();

    protected DAO() {
    }

    @SuppressWarnings("unchecked")
    public static Session getSession() throws Exception {
        Session ses = (Session) DAO.session.get();
        if (ses == null) {
            ses = sessionFactory.openSession();
            DAO.session.set(ses);
            log.debug("New Hibernate Session Created.");
        }
        return ses;
    }

    protected void begin() throws Exception {
        getSession().beginTransaction();
        log.debug("A Hibernate Transaction Began.");
    }

    protected void commit() throws Exception {
        if (!getSession().getTransaction().wasCommitted()) {
            getSession().getTransaction().commit();
            log.debug("A Hibernate Transaction was Comitted.");
        }
    }

    @SuppressWarnings("unchecked")
    protected void rollback() throws Exception {
        if (!getSession().getTransaction().wasRolledBack()) {
            getSession().getTransaction().rollback();
            getSession().close();
            DAO.session.set(null);
            log.debug("A Hibernate Transaction was Rolledback.");
        }
    }

    @SuppressWarnings("unchecked")
    public static void flush() throws Exception {
        getSession().flush();
    }

    public static void close() throws Exception {
        getSession().close();
        DAO.session.set(null);
        log.debug("Hibernate Session closed.");
    }
}